package com.eastmoney.emis.edda.infrastructure.edda.service;

import com.eastmoney.emis.edda.domain.valueobject.RejectReasonCode;
import com.eastmoney.emis.edda.infrastructure.exception.EddaException;
import com.eastmoney.emis.edda.infrastructure.exception.EddaExceptionStatus;
import com.eastmoney.emis.edda.infrastructure.hsbc.dto.HsbcEddaBaseResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: Description
 * @projectName: EDDA-HSBC
 * @package: com.eastmoney.emis.edda.infrastructure.edda.service
 * @author: 汪程程
 * @date: 2022/10/12 4:26 PM
 * @version: 1.0
 */
@Component
public class HsbcApiErrorResolver {

    private static final Logger log = LoggerFactory.getLogger(HsbcApiErrorResolver.class);
    private final Map<String, RejectReasonCode> rejectReasonCodeMap = new HashMap<>();

    @PostConstruct
    public void initMap() {
        for (RejectReasonCode code : RejectReasonCode.values()) {
            rejectReasonCodeMap.put(code.name(), code);
        }
    }

    public void resolveAndTrow(HsbcEddaBaseResp hsbcEddaBaseResp) throws EddaException {
        if (hsbcEddaBaseResp.success()) {
            return;
        }
        if (!ObjectUtils.isEmpty(hsbcEddaBaseResp.Errors)) {
            log.warn("请求汇丰api错误, {}", hsbcEddaBaseResp.Errors);
            for (HsbcEddaBaseResp.HsbcEddaError hsbcEddaError : hsbcEddaBaseResp.Errors) {
                RejectReasonCode code = rejectReasonCodeMap.get(hsbcEddaError.ErrorCode);
                if (code != null) {
                    throw new EddaException(code.exceptionStatus(), code.formatMessage());
                }
            }
        }

        throw new EddaException(EddaExceptionStatus.ERROR, hsbcEddaBaseResp.errors(), true);
    }


}
